﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Source.Controllers
{
    public class MainController : Controller
    {
        private DbSchema _Database;

        public MainController()
        {
            _Database = new DbSchema();
        }

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        #region Methods (Profile)        
        [HttpPost]
        public JsonResult GetAllProfiles()
        {
            var Profiles = _Database.Profiles.ToList();
            var Relations = _Database.ProfilesTeams.ToList();
            _Database.Teams.ToList();

            foreach (var Profile in Profiles)
            {
                var TeamsForProfile = Relations.Where(g => g.ProfileId == Profile.Id).Select(g => g.Team).ToList();
                Profile.Teams = TeamsForProfile;
            }

            return Json(Profiles);
        }

        [HttpPost]
        public void CreateProfile(string name)
        {
            _Database.Profiles.Add(new Profile { Name = name});
            _Database.SaveChanges();
        }

        [HttpPost]
        public void RemoveProfile(int profileId)
        {
            _Database.Profiles.Remove(_Database.Profiles.Find(profileId));
            _Database.SaveChanges();
        }
        #endregion

        #region Methods (Team)
        [HttpPost]
        public void CreateTeam(string teamName, string teamDescription)
        {
            _Database.Teams.Add(new Team { Name = teamName, Description = teamDescription });
            _Database.SaveChanges();
        }

        [HttpPost]
        public JsonResult GetAllTeams()
        {
            return Json(_Database.Teams.ToList());
        }

        [HttpPost]
        public void RemoveTeam(int teamId)
        {
            _Database.Teams.Remove(_Database.Teams.Find(teamId));
            _Database.SaveChanges();
        }

        [HttpPost]
        public void JoinTeam(int profileId, int teamId)
        {
            _Database.ProfilesTeams.Add(new ProfileTeam { ProfileId = profileId, TeamId = teamId});
            _Database.SaveChanges();
        }
        #endregion
    }
}